const query = require('../../db/db')
const bcrypt = require('bcryptjs')
//导入joi包
const joi = require('joi')
// 定义验证规则
const schema = joi.object({
    password: joi.string().pattern(/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/).required().allow('.'),

})

//修改个人信息
exports.updUser = async (req, res) => {
    try {
        const email = req.auth.email
        const key = req.body.key
        let newValue = req.body.newValue
        if (key === 'password') {
            var b = schema.validate({ password: newValue })
            if (b.error) {
                return res.cc(b.error.message)
            }
            newValue = bcrypt.hashSync(userinfo.password, 10)
        }
        if (key === 'nickname') {
            if (newValue.length > 6) {
                return res.cc('昵称不得超过六个字符')
            }
        }
        const updEmail = `update ev_users_email set ${key}=? where email=?`
        const result = await query(updEmail, [newValue, email])
        if (key === 'nickname') {
            const searchDiscuss = 'select * from discuss where email=?'
            const searchResult = await query(searchDiscuss, email)
            if (searchResult.length) {
                const updDis = `update discuss set ${key}=? where email=?`
                const result = await query(updDis, [newValue, email])
            }

            const searchReeply = 'select * from reply_discuss where email=?'
            const replyResult = await query(searchReeply, email)
            if (replyResult.length) {
                const updReply = `update reply_discuss set ${key}=? where email=?`
                const result = await query(updReply, [newValue, email])
            }
            const searchs = 'select * from reply_discuss where replyEmail=?'
            const resss = await query(searchs, email)
            if (resss.length) {
                const updReply = `update reply_discuss set replyNickname=? where replyEmail=?`
                const result = await query(updReply, [newValue, email])
            }
        }

        if (result.affectedRows < 1) {
            return res.cc('修改失败')
        }
        res.send({
            status: 0,
            data: '修改成功'
        })
    } catch (error) {
        console.log(error);
        res.send('服务器异常')
    }
}
